package me.cxlr.qinlauncher2;

import android.app.Application;
import android.content.Intent;
import android.content.IntentFilter;

import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.DiskLogAdapter;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import io.realm.Realm;
import me.cxlr.qinlauncher2.constants.Constants;
import me.cxlr.qinlauncher2.constants.LauncherAction;
import me.cxlr.qinlauncher2.dao.ActionDao;
import me.cxlr.qinlauncher2.dao.AppDao;
import me.cxlr.qinlauncher2.dao.DockActionDao;
import me.cxlr.qinlauncher2.dao.KeyActionDao;
import me.cxlr.qinlauncher2.manager.SoftwareManager;
import me.cxlr.qinlauncher2.model.Action;
import me.cxlr.qinlauncher2.model.App;
import me.cxlr.qinlauncher2.model.DockAction;
import me.cxlr.qinlauncher2.model.KeyAction;
import me.cxlr.qinlauncher2.receiver.AppReceiver;
import me.cxlr.qinlauncher2.util.SharedPreferencesUtil;

/**
 * @author 酷安用户:山轮纸
 */
public class MyApplication extends Application {
    private static MyApplication application;

    @Override
    public void onCreate() {
        super.onCreate();

        application = this;

        Logger.addLogAdapter(new AndroidLogAdapter());
        Logger.addLogAdapter(new DiskLogAdapter());
        Logger.v("init Logger passed");

        // 初始化数据库
        Realm.init(this);
        Logger.v("init Realm passed");

        // 初始化数据库数据
        this.initDataBase();

        // 监听应用安装、卸载、更新和变化
        this.setReceiver();
    }

    /**
     * 获取Application
     *
     * @return Application
     */
    public static MyApplication getInstance() {
        return application;
    }

    private AppReceiver receiver;

    /**
     * 监听应用安装、卸载、更新和变化
     */
    private void setReceiver() {
        receiver = new AppReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
        intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
        intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
        intentFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
        intentFilter.addDataScheme("package");
        registerReceiver(receiver, intentFilter);
        Logger.v("setReceiver passed");
    }

    /**
     * 初始化数据库数据
     */
    private void initDataBase() {
        boolean firstInitFlag = SharedPreferencesUtil.getInstance().getBoolean("flag_first_init", true);
        // 初始化
        if (firstInitFlag) {
            initAppData();
            initActionData();
            initKeyActionData();
            initDockActionData();
            tuneUpData();
            SharedPreferencesUtil.getInstance().setBoolean("flag_first_init", false);
        }
        // 新版本添加数据(在这加)
        initDate4VersionCode18();
        Logger.v("initDataBase passed");
    }

    /**
     * 初始化应用程序数据
     */
    private void initAppData() {
        List<App> appArrayList = SoftwareManager.getInstance().getApplicationList();

        AppDao appDao = new AppDao();
        appDao.saveApp(appArrayList);
    }

    /**
     * 初始化启动器提供的动作
     */
    private void initActionData() {
        ArrayList<Action> actionList = new ArrayList<>(16);
        actionList.add(Action.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).actionName(LauncherAction.NO.getAction()).resLabel(LauncherAction.NO.getResLabel()).build());
        actionList.add(Action.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).actionName(LauncherAction.SHORT_LINE.getAction()).resLabel(LauncherAction.SHORT_LINE.getResLabel()).build());
        actionList.add(Action.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).actionName(LauncherAction.APP_DRAWER.getAction()).resLabel(LauncherAction.APP_DRAWER.getResLabel()).build());
        actionList.add(Action.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).actionName(LauncherAction.VOLUME.getAction()).resLabel(LauncherAction.VOLUME.getResLabel()).build());
        actionList.add(Action.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).actionName(LauncherAction.FLASHLIGHT.getAction()).resLabel(LauncherAction.FLASHLIGHT.getResLabel()).build());
        actionList.add(Action.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).actionName(LauncherAction.LAUNCHER_SETTINGS.getAction()).resLabel(LauncherAction.LAUNCHER_SETTINGS.getResLabel()).build());

        ActionDao actionDao = new ActionDao();
        actionDao.saveAction(actionList);
    }

    /**
     * 初始化物理按键
     */
    private void initKeyActionData() {
        ArrayList<KeyAction> keyActionList = new ArrayList<>(16);

        keyActionList.add(KeyAction.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).keyName(Constants.FUNCTION_KEY_MENU).keyType(Constants.KEY_TYPE_FUNCTION_KEY).actionType(Constants.KEY_ACTION_TYPE_NO).app(null).action(null).build());
        keyActionList.add(KeyAction.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).keyName(Constants.FUNCTION_KEY_MENU_LONG).keyType(Constants.KEY_TYPE_FUNCTION_KEY).actionType(Constants.KEY_ACTION_TYPE_NO).app(null).action(null).build());
        keyActionList.add(KeyAction.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).keyName(Constants.FUNCTION_KEY_BACK).keyType(Constants.KEY_TYPE_FUNCTION_KEY).actionType(Constants.KEY_ACTION_TYPE_NO).app(null).action(null).build());

        keyActionList.add(KeyAction.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).keyName(Constants.DPAD_KEY_UP).keyType(Constants.KEY_TYPE_DPAD).actionType(Constants.KEY_ACTION_TYPE_NO).app(null).action(null).build());
        keyActionList.add(KeyAction.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).keyName(Constants.DPAD_KEY_DOWN).keyType(Constants.KEY_TYPE_DPAD).actionType(Constants.KEY_ACTION_TYPE_NO).app(null).action(null).build());
        keyActionList.add(KeyAction.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).keyName(Constants.DPAD_KEY_LEFT).keyType(Constants.KEY_TYPE_DPAD).actionType(Constants.KEY_ACTION_TYPE_NO).app(null).action(null).build());
        keyActionList.add(KeyAction.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).keyName(Constants.DPAD_KEY_RIGHT).keyType(Constants.KEY_TYPE_DPAD).actionType(Constants.KEY_ACTION_TYPE_NO).app(null).action(null).build());

        keyActionList.add(KeyAction.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).keyName(Constants.NUMBER_KEY_0).keyType(Constants.KEY_TYPE_NUMBER_KEY_SHORT).actionType(Constants.KEY_ACTION_TYPE_NO).app(null).action(null).build());
        keyActionList.add(KeyAction.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).keyName(Constants.NUMBER_KEY_1).keyType(Constants.KEY_TYPE_NUMBER_KEY_SHORT).actionType(Constants.KEY_ACTION_TYPE_NO).app(null).action(null).build());
        keyActionList.add(KeyAction.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).keyName(Constants.NUMBER_KEY_2).keyType(Constants.KEY_TYPE_NUMBER_KEY_SHORT).actionType(Constants.KEY_ACTION_TYPE_NO).app(null).action(null).build());
        keyActionList.add(KeyAction.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).keyName(Constants.NUMBER_KEY_3).keyType(Constants.KEY_TYPE_NUMBER_KEY_SHORT).actionType(Constants.KEY_ACTION_TYPE_NO).app(null).action(null).build());
        keyActionList.add(KeyAction.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).keyName(Constants.NUMBER_KEY_4).keyType(Constants.KEY_TYPE_NUMBER_KEY_SHORT).actionType(Constants.KEY_ACTION_TYPE_NO).app(null).action(null).build());
        keyActionList.add(KeyAction.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).keyName(Constants.NUMBER_KEY_5).keyType(Constants.KEY_TYPE_NUMBER_KEY_SHORT).actionType(Constants.KEY_ACTION_TYPE_NO).app(null).action(null).build());
        keyActionList.add(KeyAction.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).keyName(Constants.NUMBER_KEY_6).keyType(Constants.KEY_TYPE_NUMBER_KEY_SHORT).actionType(Constants.KEY_ACTION_TYPE_NO).app(null).action(null).build());
        keyActionList.add(KeyAction.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).keyName(Constants.NUMBER_KEY_7).keyType(Constants.KEY_TYPE_NUMBER_KEY_SHORT).actionType(Constants.KEY_ACTION_TYPE_NO).app(null).action(null).build());
        keyActionList.add(KeyAction.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).keyName(Constants.NUMBER_KEY_8).keyType(Constants.KEY_TYPE_NUMBER_KEY_SHORT).actionType(Constants.KEY_ACTION_TYPE_NO).app(null).action(null).build());
        keyActionList.add(KeyAction.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).keyName(Constants.NUMBER_KEY_9).keyType(Constants.KEY_TYPE_NUMBER_KEY_SHORT).actionType(Constants.KEY_ACTION_TYPE_NO).app(null).action(null).build());
        keyActionList.add(KeyAction.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).keyName(Constants.NUMBER_KEY_STAR).keyType(Constants.KEY_TYPE_NUMBER_KEY_SHORT).actionType(Constants.KEY_ACTION_TYPE_NO).app(null).action(null).build());
        keyActionList.add(KeyAction.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).keyName(Constants.NUMBER_KEY_POUND).keyType(Constants.KEY_TYPE_NUMBER_KEY_SHORT).actionType(Constants.KEY_ACTION_TYPE_NO).app(null).action(null).build());

        keyActionList.add(KeyAction.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).keyName(Constants.NUMBER_KEY_LONG_0).keyType(Constants.KEY_TYPE_NUMBER_KEY_LONG).actionType(Constants.KEY_ACTION_TYPE_NO).app(null).action(null).build());
        keyActionList.add(KeyAction.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).keyName(Constants.NUMBER_KEY_LONG_1).keyType(Constants.KEY_TYPE_NUMBER_KEY_LONG).actionType(Constants.KEY_ACTION_TYPE_NO).app(null).action(null).build());
        keyActionList.add(KeyAction.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).keyName(Constants.NUMBER_KEY_LONG_2).keyType(Constants.KEY_TYPE_NUMBER_KEY_LONG).actionType(Constants.KEY_ACTION_TYPE_NO).app(null).action(null).build());
        keyActionList.add(KeyAction.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).keyName(Constants.NUMBER_KEY_LONG_3).keyType(Constants.KEY_TYPE_NUMBER_KEY_LONG).actionType(Constants.KEY_ACTION_TYPE_NO).app(null).action(null).build());
        keyActionList.add(KeyAction.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).keyName(Constants.NUMBER_KEY_LONG_4).keyType(Constants.KEY_TYPE_NUMBER_KEY_LONG).actionType(Constants.KEY_ACTION_TYPE_NO).app(null).action(null).build());
        keyActionList.add(KeyAction.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).keyName(Constants.NUMBER_KEY_LONG_5).keyType(Constants.KEY_TYPE_NUMBER_KEY_LONG).actionType(Constants.KEY_ACTION_TYPE_NO).app(null).action(null).build());
        keyActionList.add(KeyAction.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).keyName(Constants.NUMBER_KEY_LONG_6).keyType(Constants.KEY_TYPE_NUMBER_KEY_LONG).actionType(Constants.KEY_ACTION_TYPE_NO).app(null).action(null).build());
        keyActionList.add(KeyAction.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).keyName(Constants.NUMBER_KEY_LONG_7).keyType(Constants.KEY_TYPE_NUMBER_KEY_LONG).actionType(Constants.KEY_ACTION_TYPE_NO).app(null).action(null).build());
        keyActionList.add(KeyAction.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).keyName(Constants.NUMBER_KEY_LONG_8).keyType(Constants.KEY_TYPE_NUMBER_KEY_LONG).actionType(Constants.KEY_ACTION_TYPE_NO).app(null).action(null).build());
        keyActionList.add(KeyAction.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).keyName(Constants.NUMBER_KEY_LONG_9).keyType(Constants.KEY_TYPE_NUMBER_KEY_LONG).actionType(Constants.KEY_ACTION_TYPE_NO).app(null).action(null).build());
        keyActionList.add(KeyAction.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).keyName(Constants.NUMBER_KEY_LONG_STAR).keyType(Constants.KEY_TYPE_NUMBER_KEY_LONG).actionType(Constants.KEY_ACTION_TYPE_NO).app(null).action(null).build());
        keyActionList.add(KeyAction.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).keyName(Constants.NUMBER_KEY_LONG_POUND).keyType(Constants.KEY_TYPE_NUMBER_KEY_LONG).actionType(Constants.KEY_ACTION_TYPE_NO).app(null).action(null).build());

        KeyActionDao keyActionDao = new KeyActionDao();
        keyActionDao.saveKeyAction(keyActionList);
    }

    /**
     * 初始化Dock的功能
     */
    private void initDockActionData() {
        ArrayList<DockAction> dockActionList = new ArrayList<>(16);
        dockActionList.add(DockAction.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).iconName("icon1").iconNumber(Constants.DOCK_ICON_NUMBER_3).actionType(Constants.DOCK_ACTION_TYPE_NO).app(null).action(null).build());
        dockActionList.add(DockAction.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).iconName("icon2").iconNumber(Constants.DOCK_ICON_NUMBER_3).actionType(Constants.DOCK_ACTION_TYPE_NO).app(null).action(null).build());
        dockActionList.add(DockAction.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).iconName("icon3").iconNumber(Constants.DOCK_ICON_NUMBER_3).actionType(Constants.DOCK_ACTION_TYPE_NO).app(null).action(null).build());

        dockActionList.add(DockAction.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).iconName("icon1").iconNumber(Constants.DOCK_ICON_NUMBER_5).actionType(Constants.DOCK_ACTION_TYPE_NO).app(null).action(null).build());
        dockActionList.add(DockAction.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).iconName("icon2").iconNumber(Constants.DOCK_ICON_NUMBER_5).actionType(Constants.DOCK_ACTION_TYPE_NO).app(null).action(null).build());
        dockActionList.add(DockAction.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).iconName("icon3").iconNumber(Constants.DOCK_ICON_NUMBER_5).actionType(Constants.DOCK_ACTION_TYPE_NO).app(null).action(null).build());
        dockActionList.add(DockAction.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).iconName("icon4").iconNumber(Constants.DOCK_ICON_NUMBER_5).actionType(Constants.DOCK_ACTION_TYPE_NO).app(null).action(null).build());
        dockActionList.add(DockAction.builder().id(UUID.randomUUID().toString().replaceAll("-", "")).iconName("icon5").iconNumber(Constants.DOCK_ICON_NUMBER_5).actionType(Constants.DOCK_ACTION_TYPE_NO).app(null).action(null).build());

        DockActionDao dockActionDao = new DockActionDao();
        dockActionDao.saveDockAction(dockActionList);
    }

    /**
     * 调整数据
     */
    private void tuneUpData() {
        ActionDao actionDao = new ActionDao();
        KeyActionDao keyActionDao = new KeyActionDao();
        DockActionDao dockActionDao = new DockActionDao();

        Action actionLauncherSettings = actionDao.findActionByActionName(LauncherAction.LAUNCHER_SETTINGS.getAction());
        if (actionLauncherSettings != null) {
            KeyAction leftFunctionKeyLong = keyActionDao.findKeyActionByKeyNameAndKeyType(Constants.FUNCTION_KEY_MENU_LONG, Constants.KEY_TYPE_FUNCTION_KEY);
            if (leftFunctionKeyLong != null) {
                leftFunctionKeyLong.setAction(actionLauncherSettings);
                leftFunctionKeyLong.setActionType(Constants.KEY_ACTION_TYPE_ACTION);
                keyActionDao.updateKeyAction(leftFunctionKeyLong);
            }
        }

        Action actionOpenAppDrawer = actionDao.findActionByActionName(LauncherAction.APP_DRAWER.getAction());
        if (actionOpenAppDrawer != null) {
            KeyAction leftFunctionKey = keyActionDao.findKeyActionByKeyNameAndKeyType(Constants.FUNCTION_KEY_MENU, Constants.KEY_TYPE_FUNCTION_KEY);
            if (leftFunctionKey != null) {
                leftFunctionKey.setAction(actionOpenAppDrawer);
                leftFunctionKey.setActionType(Constants.KEY_ACTION_TYPE_ACTION);
                keyActionDao.updateKeyAction(leftFunctionKey);
            }
        }

        Action actionVolume = actionDao.findActionByActionName(LauncherAction.VOLUME.getAction());
        if (actionVolume != null) {
            KeyAction rightFunctionKey = keyActionDao.findKeyActionByKeyNameAndKeyType(Constants.FUNCTION_KEY_BACK, Constants.KEY_TYPE_FUNCTION_KEY);
            if (rightFunctionKey != null) {
                rightFunctionKey.setAction(actionVolume);
                rightFunctionKey.setActionType(Constants.KEY_ACTION_TYPE_ACTION);
                keyActionDao.updateKeyAction(rightFunctionKey);
            }
        }

        Action actionAppDrawer = actionDao.findActionByActionName(LauncherAction.APP_DRAWER.getAction());
        if (actionAppDrawer != null) {
            DockAction dockAction2 = dockActionDao.findDockActionByIconNumberAndIconName(3, "icon2");
            dockAction2.setActionType(2);
            dockAction2.setAction(actionAppDrawer);
            dockActionDao.updateDockAction(dockAction2);

            DockAction dockAction3 = dockActionDao.findDockActionByIconNumberAndIconName(5, "icon3");
            dockAction3.setActionType(2);
            dockAction3.setAction(actionAppDrawer);
            dockActionDao.updateDockAction(dockAction3);
        }
    }

    /**
     * 增加版本号为18的新数据
     */
    private void initDate4VersionCode18() {
        boolean flagVersionCode18 = SharedPreferencesUtil.getInstance().getBoolean("init_version_18", true);
        int versionCode = SoftwareManager.getInstance().getLauncherVersionCode();
        if (flagVersionCode18 && (versionCode >= 18)) {
            ActionDao actionDao = new ActionDao();
            Action action = Action.builder()
                    .id(UUID.randomUUID().toString().replaceAll("-", ""))
                    .actionName(LauncherAction.OPEN_NOTIFICATION.getAction())
                    .resLabel(LauncherAction.OPEN_NOTIFICATION.getResLabel())
                    .build();
            actionDao.saveAction(action);
            SharedPreferencesUtil.getInstance().setBoolean("init_version_18", false);
        }
    }
}
